package cn.wolfcode.realm;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component  //将MyRealm交给spring ioc管理
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IEmployeeService employeeService;
    @Autowired
    private IPermissionService permissionService;


    //权限
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        //获取当前的主体对象
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //是否管理员
        if (employee.isAdmin()){
            info.addRole("admin");
            //权限 根据数据库中的表达式来填写
            info.addStringPermission("*:*");
            return info;
        }
        //获取当前的用户角色
        List<String> rolesnlist = roleService.getRoleSnByEmployeeId(employee.getId());

        //获取当前用户的权限
        List<String> permissionList = permissionService.getPermissionExpressionByEmployeeId(employee.getId());
        //给当前用户添加角色和权限（授权）
        info.addRoles(rolesnlist);
        info.addStringPermissions(permissionList);
        return null;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)
            throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) authenticationToken;
        Employee employee = employeeService.selectByUsername(usernamePasswordToken.getUsername());
        if (employee == null){
            return null;
        }else {
            //对象  密码（根据数据库查询出来）
            //认证成功 到授权方法 授权方法就会得到employee对象作为参数
            /*AuthenticationInfo info =
                    new SimpleAuthenticationInfo(employee,employee.getPassword(),this.getName());*/
            AuthenticationInfo info =
                    new SimpleAuthenticationInfo(employee,employee.getPassword(),
                            ByteSource.Util.bytes(employee.getName()),this.getName());

            return info;
        }
    }

    //获取用户的密钥 、盐  创建含有密钥和盐的对象 进行登录验证
    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher){
        super.setCredentialsMatcher(credentialsMatcher);
    }
}
